//
//  PHHomeViewController.m
//  PhnixHome
//
//  Created by Levy Xu on 2017/11/24.
//Copyright © 2017年 Levy Xu. All rights reserved.
//

#import "PHHomeViewController.h"
#import "PHDeviceAddViewController.h"
#import "EWHMainViewController.h"
#import "PHLocation.h"
#import "PHAds.h"
#import "GizManager.h"
#import "WPMainViewController.h"
#import "KKHomeButton.h"

#define kHeaderHeight (SCREEN_WIDTH * (9.0f / 16.0f))

@interface PHHomeViewController ()<SDCycleScrollViewDelegate>
@property (nonatomic, strong) UIImageView *topImageView;
@property (nonatomic, strong) UIView *shadowView;
@property (nonatomic, strong) SDCycleScrollView *cycleSV;
@property (nonatomic, strong) UIView *middleView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) QMUIButton *addBtn;
@property (nonatomic, strong) NSMutableArray *deviceArray;
@end

@implementation PHHomeViewController

- (void)didInitialized {
    [super didInitialized];
    
    _deviceArray = [NSMutableArray array];
    
    [NNCDC addObserver:self selector:@selector(refreshButtons) name:kDeviceCountChangedNotification object:nil];
    [NNCDC addObserver:self selector:@selector(refreshButtons) name:kGizDeviceListChangedNotification object:nil];
}


- (void)initSubviews {
    [super initSubviews];
    
    self.topImageView = [[UIImageView alloc] initWithImage:UIImageMake(@"top_background")];
    [self.view addSubview:self.topImageView];
    
    self.shadowView = [[UIView alloc] init];
    self.shadowView.backgroundColor = UIColorClear;
    [self.shadowView showShadow];
    [self.view addSubview:self.shadowView];
    
    self.cycleSV = [[SDCycleScrollView alloc] init];
    self.cycleSV.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    self.cycleSV.currentPageDotColor = [UIColor whiteColor];
    self.cycleSV.autoScrollTimeInterval = 5.0f;
    self.cycleSV.placeholderImage = UIImageMake(@"Banner1");
    [self.cycleSV showCornerRadius];
    [self.shadowView addSubview:self.cycleSV];
    
    self.middleView = [[UIView alloc] init];
    [self.view addSubview:self.middleView];
    
    self.addBtn = [[QMUIButton alloc] init];
    self.addBtn.backgroundColor = [UIColor whiteColor];
    self.addBtn.adjustsImageTintColorAutomatically = YES;
    self.addBtn.imagePosition = QMUIButtonImagePositionLeft;
    [self.addBtn setImage:UIImageMake(@"icon_add") forState:UIControlStateNormal];
    self.addBtn.titleLabel.font = CodeFontMake(16);
    [self.addBtn setTitle:NSLocalizedString(@"btn_add_device", nil) forState:UIControlStateNormal];
    [self.addBtn addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
    [self.addBtn showCornerRadius];
    [self.addBtn showShadow];
    [self.view addSubview:self.addBtn];
    
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
    [self.view addSubview:self.scrollView];
}

-(void)refreshButtons {
    [_deviceArray removeAllObjects];
    [_deviceArray addObjectsFromArray:[GPHDeviceManager deviceList]];
    [_deviceArray addObjectsFromArray:[[GizWifiSDK sharedInstance] deviceList]];
    
    [self.scrollView removeAllSubviews];
    for (int i = 0; i < _deviceArray.count; i++) {
        KKHomeButton *button = [[KKHomeButton alloc] init];
        button.model = _deviceArray[i];
        button.tag = 1000 + i;
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:button];
    }
    [self.view setNeedsLayout];
}

- (void)buttonClicked:(KKHomeButton *)button {
    if ([button.model isKindOfClass:[GizWifiDevice class]]) {
        WPMainViewController *wpVC = [[WPMainViewController alloc] initWithModel:button.model];
        [self.navigationController pushViewController:wpVC animated:YES];
    } else if ([button.model isKindOfClass:[PHDevice class]]) {
        PHDevice *model = button.model;
        if (model.device_type == PHDeviceTypeWaterHeater) {
            EWHMainViewController *mainVC = [[EWHMainViewController alloc] initWithDeviceModel:button.model];
            [self.navigationController pushViewController:mainVC animated:YES];
        }
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    CGFloat contentMinY = self.qmui_navigationBarMaxYInViewCoordinator;
    CGFloat tabHeight = self.qmui_tabBarSpacingInViewCoordinator;
    self.topImageView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * 344 / 750);
    CGFloat width = SCREEN_WIDTH - 2 * kHorizontalMargin;
    self.shadowView.frame = CGRectMake(kHorizontalMargin, contentMinY, width, floorf(width * 9 / 16));
    self.cycleSV.frame = self.shadowView.bounds;
    self.middleView.frame = CGRectMake(kHorizontalMargin, self.shadowView.qmui_bottom, width, 0);
    
    NSInteger count1 = [GPHDeviceManager deviceList].count;
    NSInteger count2 = [[GizWifiSDK sharedInstance] deviceList].count;
    NSInteger count = count1 + count2;
    if (count == 0) {
        self.scrollView.hidden = YES;
        self.addBtn.hidden = NO;
        self.addBtn.frame = CGRectMake(kHorizontalMargin, self.middleView.qmui_bottom + 10, width, 120);
        self.addBtn.contentEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0);
    } else {
        self.scrollView.hidden = NO;
        self.addBtn.hidden = YES;
        
        CGFloat scrollHeight = SCREEN_HEIGHT - self.middleView.qmui_bottom - tabHeight;
        self.scrollView.frame = CGRectMake(0, self.middleView.qmui_bottom, SCREEN_WIDTH, scrollHeight);
        if (count == 1) {
            self.scrollView.contentSize = CGRectInset(self.scrollView.frame, kHorizontalMargin, kHorizontalMargin).size;
            for (UIView *view in self.scrollView.subviews) {
                if ([view isKindOfClass:[KKHomeButton class]]) {
                    view.frame = (CGRect){ 0, 0, self.scrollView.contentSize };
                }
            }
        } else {
            CGFloat buttonWidth = (self.scrollView.qmui_width - 3 * kHorizontalMargin) / 2.0;
            CGFloat buttonHeight = IS_35INCH_SCREEN
            ? self.scrollView.qmui_height - 2 * kHorizontalMargin
            : (self.scrollView.qmui_height - 3 * kHorizontalMargin) / 2.0;
            
            NSInteger total = count / 2 + count % 2;
            self.scrollView.contentSize = CGSizeMake(self.scrollView.qmui_width - 2 * kHorizontalMargin,
                                                     buttonHeight * total + kHorizontalMargin * (total - 1));
            
            for (UIView *view in self.scrollView.subviews) {
                NSInteger tag = view.tag - 1000;
                if (tag >= 0 && [view isKindOfClass:[KKHomeButton class]]) {
                    view.frame = CGRectMake((buttonWidth + kHorizontalMargin) * (tag % 2),
                                              (buttonHeight + kHorizontalMargin) * (tag / 2),
                                              buttonWidth,
                                              buttonHeight);
                }
            }
        }
    }
    
    [self.view bringSubviewToFront:self.shadowView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self refreshButtons];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WS(ws);
    [PHAdsManager requestAds:^(NSArray *ads) {
        if (ads) {
            NSMutableArray *images = [NSMutableArray array];
            for (PHAds *ad in ads) {
                [images addObject:ad.path];
            }
            ws.cycleSV.imageURLStringsGroup = images;
        }
    }];
}

- (void)setupNavigationItems {
    self.title = NSLocalizedString(@"title_home", nil);
    self.navRightImage = UIImageMake(@"icon_add");
    [super setupNavigationItems];
}

- (void)rightAction {
    PHDeviceAddViewController *addVC = [[PHDeviceAddViewController alloc] init];
    [self.navigationController pushViewController:addVC animated:YES];
}
@end
